package main

import (
	"fmt"
	"time"

	"github.com/kataras/iris"
	"github.com/kataras/iris/middleware/logger"
	"github.com/kataras/iris/middleware/recover"
	"github.com/kataras/iris/mvc"
	"github.com/kataras/iris/sessions"
)

type VisitController struct {
	Session   *sessions.Session
	StartTime time.Time
}

func (c *VisitController) Get() string {
	visits := c.Session.Increment("visits", 1)
	since := time.Now().Sub(c.StartTime).Seconds()
	return fmt.Sprintf("%d visit from my current session in %0.1f seconds of server's up-time", visits, since)
}
func newApp() *iris.Application {
	app := iris.New()
	sess := sessions.New(sessions.Config{Cookie: "mysession_cookie_name"})
	visitApp := mvc.New(app.Party("/"))
	visitApp.Register(sess.Start, time.Now())
	visitApp.Handle(new(VisitController))
	return app
}
func main() {

	app := iris.New()

	app.Use(recover.New())
	app.Use(logger.New())

	app.Handle("GET", "/welcome", func(ctx iris.Context) {
		ctx.HTML("<h1>Welcome</h1>")
	})
	app.Get("/ping", func(ctx iris.Context) {
		ctx.WriteString("pong")
	})

	app.Get("hello", func(ctx iris.Context) {
		ctx.JSON(iris.Map{"message": "Hello Iris!"})
	})

	users := app.Party("/users", myAuthMiddlewareHandler)

	//	app.PartyFunc("/users", func(users iris.Party) {
	//		users.Use(myAuthMiddlewareHandler)
	//		users.Get("/{id:int}/profile", userProfileHandler)
	//		users.Get("/inbox/{id:int}", userMessageHandler)
	//	})
	users.Get("/{id:int}/profile", userProfileHandler)
	users.Get("/inbox/{id:int}", userMessageHandler)

	app.OnErrorCode(iris.StatusNotFound, func(ctx iris.Context) {
		ctx.HTML("<b>Resource not found </b>")

	})

	app.Run(iris.Addr(":8080"))

}

func myAuthMiddlewareHandler(ctx iris.Context) {
	ctx.WriteString("AuthMiddewareHandler failed")
	ctx.Next()
}
func userProfileHandler(ctx iris.Context) {
	id := ctx.Params().Get("id")
	ctx.WriteString(id)
}
func userMessageHandler(ctx iris.Context) {
	id := ctx.Params().Get("id")
	ctx.WriteString(id)
}
